package com.ry.BondUnpack;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class Client2 {

    public static void main(String[] args) {
        Client2 client2 = new Client2();
        try {
            client2.client();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }


    public void client() throws InterruptedException {
        EventLoopGroup boss = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(boss)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
//                        ch.pipeline().addLast("frameDecoder",new LineBasedFrameDecoder(80));
//                        ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
//                        ch.pipeline().addLast("stringDecoder",new StringDecoder());
                        ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
                        ch.pipeline().addLast("stringEncoder",new StringEncoder());
                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast(new ClientHandler());
                    }
                });

        bootstrap.bind(8081).sync();
        ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 8080);
        channelFuture.channel().closeFuture().sync();
    }

    class ClientHandler extends ChannelInboundHandlerAdapter {

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            String req = "-this is query,current time:" + System.currentTimeMillis() + System.getProperty("line.separator");
            for (int i = 0; i < 10000; i++) {
                System.out.println("发送消息" + i);
//                ByteBuf byteBuf = Unpooled.buffer((i + req).length());
//                byteBuf.writeBytes((i + req).getBytes("UTF-8"));
                ctx.writeAndFlush(i+req);
            }
        }


        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            cause.printStackTrace();
        }
    }
}
